package com.example.controller;

import com.example.pojo.SysEmp;
import com.example.pojo.SysUser;
import com.example.service.SysEmpService;
import com.example.service.SysUserService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysEmpService sysEmpService;

    //分页条件查询方法
    @RequestMapping("/list")
    public String listUsers(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "3") Integer pageSize, String LoginName,
                            String EName, Map map) {
        SysUser sysUser = new SysUser();
        sysUser.setLoginname(LoginName);
        log.info(LoginName, EName);
//        Page<SysUser> allUsers = sysUserService.findAllUsers(new Page<>(pageNum, pageSize), sysUser, EName);
        PageInfo allUsers = sysUserService.findAllUsersList(pageNum, pageSize, sysUser, EName);
        map.put("pageInfo", allUsers);
        map.put("pageNum", pageNum);
        map.put("EName", EName);
        map.put("LoginName", LoginName);
        return "/system/user/userlist";
    }

    @RequestMapping("/save")
    public String saveUser(Integer eid, String loginname, String loginpwd) {
        SysUser sysUser = new SysUser();
        sysUser.setEid(eid);
        sysUser.setLoginpwd(loginpwd);
        sysUser.setLoginname(loginname);
        sysUser.setLogintime(new Date());
        System.out.println(sysUser);
        sysUserService.save(sysUser);
        return "redirect:/user/list";
    }

    @RequestMapping(value = "/edit")
    public String editUser(Integer userid, Map map) {
        SysUser user = sysUserService.getById(userid);
        SysEmp sysEmp = sysEmpService.getById(user.getEid());
        user.setSysEmp(sysEmp);
        List<SysEmp> list = sysEmpService.list();
        log.info(user.toString());
        map.put("empList", list);
        map.put("user", user);
        return "/system/user/useredit";
    }

    @RequestMapping("/update")
    @CacheEvict(value = "UserList", allEntries = true)
    public String updateUser(SysUser sysUser) {
        log.info(sysUser.toString());
        sysUserService.updateById(sysUser);
        return "redirect:/user/list";
    }

    @RequestMapping("/delete")
    @CacheEvict(value = "UserList", allEntries = true)
    public String deleteById(Integer userid) {
        sysUserService.removeById(userid);
        return "redirect:/user/list";
    }
}
